﻿using ERP.Inventory.Api.Read.DTO;
using ERP.Inventory.Errorcode;
using ERP.Inventory.Infastructure.Interface;
using MediatR;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using ERP.Inventory.Api.Read.Application.Command.库存管理;
using ERP.Inventory.Domain.库存管理;

namespace ERP.Inventory.Api.Read.Application.Handler.库存管理
{
    public class GetCheckHandler : IRequestHandler<GetCheckCommand, ApiPaging<CheckDTO>>
    {
        private readonly IBaseRepository<CheckModel> CheckRepo;
        private readonly IBaseRepository<StoreModel> storeRepo;

        public GetCheckHandler(IBaseRepository<CheckModel> CheckRepo, IBaseRepository<StoreModel> storeRepo)
        {
            this.CheckRepo = CheckRepo;
            this.storeRepo = storeRepo;
        }

        public Task<ApiPaging<CheckDTO>> Handle(GetCheckCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPaging<CheckDTO>();
            var check = CheckRepo.GetAll().Where(x => x.IsDel == false);
            var store = storeRepo.GetAll().Where(x => x.IsDel == false);
            var linq = from a in check
                       join b in store on a.StoreId equals b.Id
                       select new CheckDTO
                       {
                           Id = a.Id,
                           InvenCode = a.InvenCode,
                           InvenState = a.InvenState,
                           Mid = a.Mid,
                           InvenType = a.InvenType,
                           StoreId = a.StoreId,
                           StoreName = b.StoreName,
                           InvenRange = a.InvenRange,
                           InvenStartTime = a.InvenStartTime,
                           InvenEndTime = a.InvenEndTime,
                           Note = a.Note,
                           AttnId = a.AttnId,
                           AttnName = a.AttnName,
                           CreateUserTime = a.CreateUserTime,
                       };
            if (!string.IsNullOrEmpty(request.InvenCode))
            {
                linq = linq.Where(x => x.InvenCode.Contains(request.InvenCode));
            }

            var totalcount = linq.Count();
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            linq = linq.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            res.totalcount = totalcount;
            res.totalpage = totalpage;
            res.Message = "显示成功";
            res.Data = linq.ToList();
            res.Code = ApiEnum.Ok;
            return Task.FromResult(res);
        }
    }
}
